package avicit.cbb.techclass.elefileupdown.service.impl;

import avicit.cbb.techclass.bigsave.action.MongoDBManager;
import avicit.cbb.techclass.dxcc.JProperties;
import avicit.cbb.techclass.elefileupdown.service.FileUploadEvent;
import avicit.platform6.api.session.SessionHelper;
import avicit.platform6.api.sysshirolog.context.ContextHolder;
import avicit.platform6.api.sysuser.dto.SysDept;
import avicit.platform6.api.sysuser.dto.SysUser;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.core.domain.BeanBase;
import avicit.platform6.core.exception.DaoException;
import avicit.platform6.core.service.ServiceBase;
import avicit.platform6.core.shiroSecurity.contextThread.ContextCommonHolder;
import avicit.platform6.modules.system.sysfileupload.domain.SysFileUpload;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>金航数码科技有限责任公司</p>
 * <p>作者：孟飞</p>
 * <p>邮箱：mengf@avicit.com</p>
 * <p>创建时间： 2014-10-21 上午9:15:45 </p>
 * <p>类说明：附件上传下载模块接口实现类</p>
 * <p>修改记录： </p>
 */
//@Component("SwfUploadEventImplCbb")
//@Transactional
@Service("fileUploadEventCbb")
public class FileUploadEventImpl extends ServiceBase implements FileUploadEvent {

	@Autowired(required = true)
	private JdbcTemplate jdbcTemplate;

	@Autowired(required = true)
	private MongoDBManager mongoDBManager;

	/**
	 * 存到数据库之后的后处理 add by wangxu
	 * @param sysFileUpload
	 * @throws
	 */
	@Override
	public void afterSaveFileByDB(SysFileUpload sysFileUpload) {
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();
		try {
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				//保存文件转换信息
				this.saveCbbFileSwf(id, "");
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 存到磁盘之后的后处理 add by wangxu
	 * @param sysFileUpload
	 * @throws
	 */
	@Override
	public void afterSaveFileByDisk(SysFileUpload sysFileUpload) {
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();
		try {
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				//保存文件转换信息
				this.saveCbbFileSwf(id, "");
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	/**
	 * 存到fastdfs之后的后处理 add by wangxu
	 * @param sysFileUpload 
	 * @throws
	 */
	@Override
	public void afterSaveFileByFastdfs(SysFileUpload sysFileUpload) {
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();
		try {
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				//保存文件转换信息
				this.saveCbbFileSwf(id, "");
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 存到MongoDB服务器的后处理
	 * @param sysFileUpload
	 * @param inputStream
	 * @param mongoId
	 * @param secretLevel
	 * @throws Exception 
	 * @throws
	 */
	@Override
	public void afterSaveFileByOther(SysFileUpload sysFileUpload, InputStream inputStream, String mongoId, String secretLevel) throws Exception {
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();

		String keyfiled = mongoDBManager.getMongoDBController(mongoId).getKeyfiled();
		Map<String, String> map = new HashMap<String, String>();
		map.put(keyfiled, id);
		map.put("secret_level", secretLevel);
		try {
			mongoDBManager.getMongoDBController(mongoId).insertGridFS(inputStream, fileName, map);
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				this.saveCbbFileSwf(id, mongoId);
			}

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 存到MongoDB服务器的后处理（根据model）
	 * @param sysFileUpload
	 * @param inputStream
	 * @param mongoId
	 * @param secretLevel
	 * @param modelName 
	 * @throws
	 */
	@Override
	public void afterSaveFileByOther(SysFileUpload sysFileUpload, InputStream inputStream, String mongoId, String secretLevel, String modelName) {
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();

		String keyfiled = mongoDBManager.getMongoDBController(mongoId).getKeyfiled();
		Map<String, String> map = new HashMap<String, String>();
		map.put(keyfiled, id);
		map.put("secret_level", secretLevel);

		try {
			mongoDBManager.getMongoDBController(mongoId).insertGridFS(inputStream, fileName, map, modelName);
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				this.saveCbbFileSwf(id, mongoId);
			}

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 保存文件转换信息
	 * @param id
	 * @param mongoId void
	 * @throws
	 */
	@SuppressWarnings("deprecation")
	public void saveCbbFileSwf(String id, String mongoId) {
		String specialColumn = ",version,created_by,creation_date,last_updated_by,last_update_date,last_update_ip,ORG_ID,DEPT_ID".toUpperCase();
		String sql = "insert into CBB_FILE_SWF(ID,ATTACH_ID,FILE_STATUS,MONGODB_ID" + specialColumn + ") values(?,?,?,?,?,?,?,?,?,?,?,?)";
		HttpServletRequest request = ContextHolder.getRequest();
		List<Object> param = new ArrayList<Object>();
		if (null != request) {
			param.add(ComUtil.getId());
			param.add(id);
			param.add("0");
			param.add(mongoId);
			param.add("1.0");// version
			param.add(SessionHelper.getLoginSysUserId(request));// created_by
			param.add(new java.util.Date());// creation_date
			param.add(SessionHelper.getLoginSysUserId(request));// last_updated_by
			param.add(new java.util.Date());// last_updated_date
			param.add(request.getHeader("x-forwarded-for") == null ? request.getRemoteAddr() : request.getHeader("x-forwarded-for"));// last_update_ip
			param.add(SessionHelper.getCurrentOrgId(request));
			param.add(SessionHelper.getCurrentDeptId(request));
		} else {
			SysUser sysUser = (SysUser) ContextCommonHolder.getAttribute(SessionHelper.SESSION_CURRENT_USER);
			SysDept sysDept = (SysDept) ContextCommonHolder.getAttribute(SessionHelper.SESSION_CURRENT_DEPT);
			param.add(ComUtil.getId());
			param.add(id);
			param.add("0");
			param.add(mongoId);
			param.add("1.0");// version
			param.add(sysUser.getId());// created_by
			param.add(new java.util.Date());// creation_date
			param.add(sysUser.getId());// last_updated_by
			param.add(new java.util.Date());// last_updated_date
			param.add("1");// last_update_ip
			param.add(sysDept.getOrgId());
			param.add(sysDept.getId());
		}
		jdbcTemplate.update(sql, param.toArray());
	}

	
	
	/**
	 * 删除数据库附件之后的后处理 add by wangxu
	 * @param sysFileUpload 
	 * @throws
	 */
	@Override
	public void afterDelFileByDB(SysFileUpload sysFileUpload) {
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();
		try {
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				//删除文件转换信息
				this.deleteCbbFileSwf(id);
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void afterDelFileByDisk(SysFileUpload sysFileUpload) {
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();
		try {
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				//删除文件转换信息
				this.deleteCbbFileSwf(id);
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 删除fastdfs服务器附件的后处理
	 * @param sysFileUpload 
	 * @throws
	 */
	@Override
	public void afterDelFileByFastdfs(SysFileUpload sysFileUpload){
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();
		try {
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				//删除文件转换信息
				this.deleteCbbFileSwf(id);
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	
	/**
	 * 删除MongoDB服务器中附件的后处理
	 * @param sysFileUpload
	 * @param mongoId 
	 * @throws
	 */
	@Override
	public void afterDelFileByOther(SysFileUpload sysFileUpload, String mongoId) {
		String fileName = sysFileUpload.getFILE_NAME();
		String id = sysFileUpload.getId();
		try {
			mongoDBManager.getMongoDBController(mongoId).deleteGridFS(id);
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (JProperties.getFileProperties("fileformat").toLowerCase().indexOf(suffix.toLowerCase()) != -1) {
				this.deleteCbbFileSwf(id);
				mongoDBManager.getMongoDBController(mongoId).deleteGridFS(id + "swf");
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除AmazonS3服务器中附件的后处理
	 * @param sysFileUpload
	 * @param mongoId 
	 * @throws
	 */
	@Override
	public void afterDelFileByAmazonS3(SysFileUpload sysFileUpload, Map<String, Object> param) {
		
	}
	
	
	/**
	 * 删除文件转换信息
	 * @param attachId void
	 * @throws
	 */
	private void deleteCbbFileSwf(String attachId) {
		String sql = "delete from cbb_file_swf where attach_id = '" + attachId + "'";
		jdbcTemplate.update(sql);
	}
	
	/**
	 * 使用AmazonS3下载单个附件
	 * @param request
	 * @param response
	 * @param mongoId 
	 * @throws
	 */
	@Override
	public void downloadOneFileByAmazonS3(HttpServletRequest request, HttpServletResponse response, Map<String, Object> param) {
		
	}

	/**
	 * 使用MongoDB下载单个附件
	 * @param request
	 * @param response
	 * @param mongoId 
	 * @throws
	 */
	@Override
	public void downloadOneFileByOther(HttpServletRequest request, HttpServletResponse response, String mongoId) {
		String fileId = request.getParameter("fileId");

		InputStream in = null;
		try {
			in = mongoDBManager.getMongoDBController(mongoId).getGridFSIOById(fileId);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (in != null) {
			BufferedInputStream bis = null;
			try {
				// in = fileBody.getBinaryStream();
				bis = new BufferedInputStream(in);
				IOUtils.copy(bis, response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (null != bis) {
						bis.close();
					}
					if (null != in) {
						in.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			try {
				response.getWriter().write("下载文件错误!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}
	/**
	 * 使用MongoDB下载单个附件
	 * @param request
	 * @param response
	 * @param mongoId
	 * @throws
	 */
	@Override
	public void downloadOneFileByAttachId(HttpServletRequest request, HttpServletResponse response, String mongoId, String attachId) {
		InputStream in = null;
		try {
			in = mongoDBManager.getMongoDBController(mongoId).getGridFSIOById(attachId);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		} catch (Exception e) {

			e.printStackTrace();
		}
		if (in != null) {
			BufferedInputStream bis = null;
			try {
				// in = fileBody.getBinaryStream();
				bis = new BufferedInputStream(in);
				avicit.platform6.modules.system.sysfileupload.util.IOUtils.copy(bis, response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (null != bis) {
						bis.close();
					}
					if (null != in) {
						in.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			try {
				response.getWriter().write("下载文件错误!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 使用MongoDB下载单个附件（根据model）
	 * @param fileId
	 * @param mongoId
	 * @param modelName
	 * @param response 
	 * @throws
	 */
	@Override
	public void downloadOneFileByOther(String fileId, String mongoId, String modelName, HttpServletResponse response) {
		InputStream in = null;
		try {
			in = mongoDBManager.getMongoDBController(mongoId).getGridFSIOById(fileId, modelName);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (in != null) {
			BufferedInputStream bis = null;
			try {
				// in = fileBody.getBinaryStream();
				bis = new BufferedInputStream(in);
				IOUtils.copy(bis, response.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (null != bis) {
						bis.close();
					}
					if (null != in) {
						in.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			try {
				response.getWriter().write("");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 修改附件密级(mongodb修改附件密级)
	 * @param oldFileMap
	 * @param mongoId 
	 * @throws
	 */
	@Override
	public void updateAttachSecret(Map<String, String> oldFileMap, String mongoId) {
		Iterator<String> it = oldFileMap.keySet().iterator();
		while (it.hasNext()) {
			String attachId = it.next();
			String secret = oldFileMap.get(attachId);

			String sql = "update sys_attachment t set t.secret_level = '" + secret + "' where t.id = '" + attachId + "'";
			this.jdbcTemplate.update(sql);

			Map<String, String> map = new HashMap<String, String>();
			map.put("secret_level", secret);
			
			this.mongoDBManager.getMongoDBController(mongoId).updateDocumentById(attachId, map);
		}
	}
	
	/**
	 * 修改附件密级(非mongodb修改附件密级)
	 * @param oldFileMap
	 * @throws
	 */
	@Override
	public void updateAttachSecretLevel(Map<String, String> oldFileMap) {
		Iterator<String> it = oldFileMap.keySet().iterator();
		while (it.hasNext()) {
			String attachId = it.next();
			String secret = oldFileMap.get(attachId);

			String sql = "update sys_attachment t set t.secret_level = '" + secret + "' where t.id = '" + attachId + "'";
			this.jdbcTemplate.update(sql);
		}
	}

	@Override
	public void downloadAllFileByOther(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub

	}

	@Override
	public void insert(BeanBase bean) throws DaoException {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(BeanBase bean) throws DaoException {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(BeanBase bean) throws DaoException {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterSaveFileByDB(SysFileUpload sysFileUpload, Map<String, Object> param) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterSaveFileByDisk(SysFileUpload sysFileUpload, Map<String, Object> param) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterSaveFileByFastdfs(SysFileUpload sysFileUpload, Map<String, Object> param) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterSaveFileByOther(SysFileUpload sysFileUpload, InputStream inputStream, String mongoId, String secretLevel, Map<String, Object> param) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void downloadOneFileByOtherForConvert(HttpServletRequest request, HttpServletResponse response, String mongoId, String fileId, String fileName) {
		// TODO Auto-generated method stub
		
	}
}
